<?php

namespace App\Store\Models\Account;

use App\Admin\Models\SiteCompany;
use App\Common\Services\Common;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Common\Services\Store\Common as StoreCommon;

class Account extends Model
{
    protected $table = 'site_accout_list';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    public static function getList(Request $request){
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['companyinfo'])->where(['is_del'=>1,'cp_id'=>$cp_id,'is_show_manger'=>1])->orderBy('create_at', 'desc');

//        $query->where(function ($query) use ($request) {
//            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
//            if(($accountinfo['type']==9 && $accountinfo['is_show_manger']==1) || $accountinfo['type']!=9){
//                $query->where('type','<>',9);
//            }
//        });

        if($request->getaccountwithoutdepartment==1){
            $query->where('type','<>',12);
        }

        $isgetall = intval($request->isgetall) ?? 0;
        $real_name = $request->real_name;
        if ($real_name != '') {
            $query->where('real_name', 'like', '%' . $real_name . '%');
        }

        $store_id = intval($request->store_id);
        if ($store_id>0) {
            $query->where(function ($q) use ($store_id) {
                $store_ids=$store_id;
                $q->where('store_ids','')->orWhereRaw('FIND_IN_SET(?,store_ids)',[$store_ids]);
            });
        }

        $d_id = $request->d_id;
        if ($d_id > 0) {
            $query->where('d_id', $d_id);
        }

        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    public static function getInfo(Request $request){
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $id = $request->id;
        $query = self::with(['companyinfo'])->where(['is_del'=>1,'cp_id'=>$cp_id])->orderBy('create_at', 'desc');
        $query->where('type','<>',9);
        $query->where('id',$id);
        $info = $query->first();
        return $info;
    }


    public function companyinfo(){
        return $this->hasOne(SiteCompany::class, 'id', 'cp_id')->select(['id','company_name']);
    }

}
